package com.pic.mgt.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class IgxUtils {
	public static long getConfirmationFileContentForFilesize(File confirmationFile) throws IOException {
		try {
			return
				Long.valueOf(FileUtils.readFileToString(confirmationFile));
		} catch (NumberFormatException e) {
			return 0;
		}
	}
	
	/**
	 * 將 Shell Command 的命令字串列轉換成為參數陣列。若參數值內容有包含空白字元(whilespace)，
	 * 則將該值放在二個雙引號(")中間即可。
	 * @param shellCmdLineStr
	 * @return
	 */
	public static String[] parseShellCommandLineStrToArray(String shellCmdLineStr) {
		List<String> commandArgList = new ArrayList<String>();

		char[] shellCmdLineCharArray = shellCmdLineStr.trim().toCharArray();

		int argOffset = 0;
		int argCount = 0;
		for (int i=0;i<shellCmdLineCharArray.length;i++) {
			if (shellCmdLineCharArray[i] == '"') {
				int quotesArgOffset = i+1;
				int quotesArgCount = 0;
				for (int y=i+1;y<shellCmdLineCharArray.length;y++) {
					if (shellCmdLineCharArray[y] == '"') {
						commandArgList.add(new String(shellCmdLineCharArray, quotesArgOffset, quotesArgCount));
						i++;
						break;
					}
					else if (y == shellCmdLineCharArray.length -1) {
						quotesArgCount++;
						commandArgList.add(new String(shellCmdLineCharArray, quotesArgOffset, quotesArgCount));
						i++;
					}
					else {
						quotesArgCount++;
						i++;
					}
				}
			}
			else if (shellCmdLineCharArray[i] == ' ') {
				if (argCount > 0) {
					commandArgList.add(new String(shellCmdLineCharArray, argOffset, argCount));	
				}
				argOffset = i + 1;
				argCount = 0;
			}
			else if (i == shellCmdLineCharArray.length -1) {
				argCount++;
				commandArgList.add(new String(shellCmdLineCharArray, argOffset, argCount));
			}
			else {
				argCount++;
			}
		}

		String[] shellCommandArgsArray = new String[commandArgList.size()];
		commandArgList.toArray(shellCommandArgsArray);
		
		return shellCommandArgsArray;
	}
}
